package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.VodProperties;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.util.UploadFileUtil;
import com.atguigu.tingshu.vo.album.TrackMediaInfoVo;
import com.qcloud.vod.VodUploadClient;
import com.qcloud.vod.model.VodUploadRequest;
import com.qcloud.vod.model.VodUploadResponse;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.vod.v20180717.VodClient;
import com.tencentcloudapi.vod.v20180717.models.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;


@Service
@Slf4j
public class VodServiceImpl implements VodService {

    @Autowired
    private VodProperties vodProperties;

    @Override
    public Map<String, Object> uploadTrack(MultipartFile file) {
        VodUploadClient client = new VodUploadClient(vodProperties.getSecretId(), vodProperties.getSecretKey());

        VodUploadRequest request = new VodUploadRequest();
        // 先将文件上传到本地
        String url = UploadFileUtil.uploadTempPath(vodProperties.getTempPath(), file);

        request.setMediaFilePath(url);
        request.setStorageRegion(vodProperties.getRegion());
        request.setSubAppId(Long.valueOf(vodProperties.getAppId()));
        request.setConcurrentUploadNumber(5);

        try {
            VodUploadResponse response = client.upload(vodProperties.getRegion(), request);
            log.info("Upload FileId = {}", response.getFileId());

            HashMap<String, Object> map = new HashMap<>();
            map.put("mediaFileId", response.getFileId());
            map.put("mediaUrl", response.getMediaUrl());
            return map;
        } catch (Exception e) {
            // 业务方进行异常处理
            log.error("Upload Err", e);
        }
        return Map.of();
    }

    @Override
    public TrackMediaInfoVo getMediaInfo(String mediaFileId) {
        try {
            // 创建认证对象
            Credential credential = new Credential(vodProperties.getSecretId(), vodProperties.getSecretKey());

            // 创建客户端对象
            VodClient client = new VodClient(credential, vodProperties.getRegion());

            // 创建请求对象
            DescribeMediaInfosRequest request = new DescribeMediaInfosRequest();
            String[] fileIds = {mediaFileId};
            request.setFileIds(fileIds);

            // 发送请求，获取响应
            DescribeMediaInfosResponse resp = client.DescribeMediaInfos(request);

            MediaInfo[] mediaInfos = resp.getMediaInfoSet();

            TrackMediaInfoVo trackMediaInfoVo = new TrackMediaInfoVo();

            if (mediaInfos != null && mediaInfos.length > 0) {
                MediaInfo mediaInfo = mediaInfos[0];
                MediaBasicInfo basicInfo = mediaInfo.getBasicInfo();

                MediaMetaData metaData = mediaInfo.getMetaData();

                trackMediaInfoVo.setSize(metaData.getSize());
                trackMediaInfoVo.setDuration(metaData.getAudioDuration());
                trackMediaInfoVo.setMediaUrl(basicInfo.getMediaUrl());
                trackMediaInfoVo.setType(basicInfo.getType());
                return trackMediaInfoVo;
            }

        } catch (Exception e) {
            log.error("获取媒体信息失败");
        }
        return null;
    }

    @Override
    public void removeMediaFile(String mediaFileId) {
        try {
            // 1.创建实例认证对象
            Credential cred = new Credential(vodProperties.getSecretId(), vodProperties.getSecretKey());

            // 2.创建删除媒体信息的vod客户端对象
            VodClient client = new VodClient(cred, vodProperties.getRegion());
            // 3.创建删除对象
            DeleteMediaRequest req = new DeleteMediaRequest();
            req.setFileId(mediaFileId);
            // 4.发起请求 并且得到响应对象
            DeleteMediaResponse resp = client.DeleteMedia(req);
            // 输出json格式的字符串回包
            System.out.println(AbstractModel.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            log.error("删除媒体信息失败：{}", e.getMessage());
            throw new GuiguException(201, "删除媒体信息失败");
        }
    }
}
